const express = require('express');
const router = express.Router();
const User = require('../models/user');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const {secret} = require('../config');
const jsonwebtoken = require('jsonwebtoken');
const redis = require('redis');
const email = require('../utils/email');
const uuid = require('uuid/v4');
const client = require('../utils/redisClient');

router.get('/active/:uid', function (req, res, next) {
    client.get(req.params.uid, function (err, reply) {
        if (err) {
            console.error('active error', err);
            res.json({
                error: {
                    message: err.name
                }
            });
        }
        if (!reply) {
            res.json({
                error: {
                    message: '链接无效，请重新发送激活邮件'
                }
            })
        }
        User.findOne({where: {name: reply}}).then(user => {
            user.update({
                validate: true
            }).then(() => {
                res.redirect('/');
            })
        })
    });
});

router.post('/signup', function (req, res, next) {
    const {username, password} = req.body;
    console.log(username,password);
    if (!User.validateName(username)) {
        res.json({
            error: {
                message: "请输入正确的邮箱"
            }
        });
    }
    bcrypt.hash(password, saltRounds, function (err, hash) {
        if (err) return new Error(err);
        User.findOrCreate({where: {name: username}, defaults: {password: hash, validate: false}})
            .spread((user, created) => {
                if (created) {
                    res.cookie('token', jsonwebtoken.sign({name: username}, secret, {expiresIn: 3000}), {httpOnly: true});
                    res.json({
                        success: {
                            message: '注册成功'
                        }
                    });

                    const uid = uuid();

                    client.set(uid, username, 'EX', 30 * 60); //30分钟有效
                    client.set(username, uid, 'EX', 30 * 60);    //用户名和UUID互为键

                    let mailOptions = {
                        from: `"JISUANJISHEJIDASAI" <313183373@qq.com>`, // sender address
                        to: username, // list of receivers
                        subject: 'Test', // Subject line
                        text: `click the url link to active your account: http://localhost:3000/users/active/${uid}`, // plain text body
                    };

                    email(mailOptions);

                } else {
                    res.json({
                        error: {
                            message: "邮箱已被注册"
                        }
                    });
                }
            });
    });
});

router.post('/signin', function (req, res, next) {
    const {username, password} = req.body;
    User.findOne({where: {name: username}}).then(async (user) => {
        if (user) {
            const authenticated = await user.checkPassword(password);
            const validated = user.checkValidate();
            if (authenticated) {
                res.cookie('token', jsonwebtoken.sign({name: username}, secret, {expiresIn: 3000}), {httpOnly: true});
                if (validated) {
                    res.json({
                        success: {
                            message: '登陆成功'
                        }
                    });
                } else {
                    res.json({
                        success: {
                            message: '账号尚未激活'
                        }
                    });
                }
            } else {
                res.json({
                    error: {
                        message: '账号或密码错误'
                    }
                })
            }
        } else {
            res.json({
                error: {
                    message: '账号或密码错误'
                }
            })
        }
    })
});


router.post('/signout', function (req, res, next) {
    if (req.user) {
        res.clearCookie('token');
        res.json({
            success: {
                message: '注销成功'
            }
        })
    } else {
        res.json({
            error: {
                message: '未登陆'
            }
        })
    }
});

router.post('/email.js', async function (req, res, next) {
    if (req.user) {
        const id = uuid();
        client.getAsync(req.user.name).then(function (r) {
            return r ? client.delAsync(r) : undefined;
        }).then(function (r) {
            return r ? client.set(req.user.name, id, 'EX', 30 * 60) : undefined;
        }).then(function (r) {
            return client.set(id, req.user.name, 'EX', 30 * 60);
        }).then(function (r) {
            res.json({
                success: {
                    message: id
                }
            });
            const mailOptions = {
                from: `"JISUANJISHEJIDASAI" <313183373@qq.com>`, // sender address
                to: req.user.name, // list of receivers
                subject: 'Test', // Subject line
                text: `click the url link to active your account: http://localhost:3000/users/active/${id}`, // plain text body
            };
            email(mailOptions);
        }).catch(function (err) {
            throw err;
        });
    } else {
        res.json({
            error: {
                message: '登陆状态失效'
            }
        })
    }
});

module.exports = router;
